﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pipes.Queries.Model.Query;
using System.Data;

namespace Pipes.Queries.Provider.Dual
{
  public class DualProvider : IProvider
  {
    public void Connect()
    {
      // Do Nothing
    }

    public System.Data.DataSet ExecuteQuery(Model.Query.Script query)
    {
      if (query.Statements.Count == 1)
      {
        var stmt = query.Statements[0] as ReadBlock;
        if (stmt != null && stmt.ReadStatements.Count == 1)
        {
          var set = new DataSet();
          var tbl = set.Tables.Add();
          DataColumn dataCol;
          object[] values = new object[stmt.ReadStatements[0].Columns.Count];
          int colIndex = 0;

          for (var i = 0; i < stmt.ReadStatements[0].Columns.Count; i++)
          {
            values[i] = stmt.ReadStatements[0].Columns[i].Expr.Evaluate();
            if (stmt.ReadStatements[0].Columns[i].Alias == null)
            {
              dataCol = new DataColumn(string.Format("Col{0:D2}", colIndex++), values[i].GetType());
            }
          }
          tbl.NewRow().ItemArray = values;
          return set;
        }
      }
      throw new NotSupportedException();
    }

    public MetaData.IMetaObject GetMetaData(IEnumerable<string> path)
    {
      return null;
    }
  }
}
